import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { LocalizationService } from '@abp/ng.core';
import { UniqueCodeSettingService } from '../../proxy/joy/erp/basic-archives/core';

@Component({
  selector: 'segment-configration-ref-entity',
  templateUrl: './segment-configration-ref-entity.component.html',
  styleUrls: ['./segment-configration-ref-entity.component.less']
})
export class SegmentConfigrationRefEntityComponent implements OnInit {
  @Input() initialValue: any;
  validateForm: FormGroup;
  segmentTypes: { value: string }[] = [];
  isConfigValid = false;

  constructor(
    private fb: FormBuilder,
    private modal: NzModalRef,
    private uniqueCodeSettingService: UniqueCodeSettingService,
    public localizationService: LocalizationService
  ) {}

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      key: [null, [Validators.required]],
      configration: ['{}', [Validators.required]]
    });

    this.uniqueCodeSettingService.getOptions().subscribe(result => {
      this.segmentTypes = result.allKeys.map(key => ({ value: key }));
      
      if (this.initialValue) {
        setTimeout(() => {
          this.validateForm.patchValue(this.initialValue);
          this.onSegmentTypeChange(this.initialValue.key);
        });
      }
    });
  }

  onSegmentTypeChange(value: string) {
    if (value) {
      const currentConfig = this.initialValue && this.initialValue.key === value 
        ? this.initialValue.configration 
        : '{}';
        
      this.validateForm.patchValue({ 
        key: value,
        configration: currentConfig 
      });
      this.isConfigValid = false;
    }
  }

  onConfigValidityChanged(isValid: boolean) {
    this.isConfigValid = isValid;
  }

  submitForm(): void {
    if (this.validateForm.valid && this.isConfigValid) {
      this.modal.close(this.validateForm.value);
    }
  }

  cancel(): void {
    this.modal.close();
  }

  protected l(key: string, ...params: string[]): string {
    return this.localizationService.instant(key, ...params);
  }
} 